<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <link rel="icon" href="./favicon.ico" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Videos</title>
        <link href="../../common/css/video.js/video-js.min.css" rel="stylesheet" />
        <link href="../../common/css/video.js/vjs-theme-sea.css" rel="stylesheet" />
        <script src="../../common/js/vue.2.6.14.min.js"></script>
        <link href="./style.css" rel="stylesheet" />
    </head>
    <body>
        <div id="app">
            <aside>
                <div class="category">
                    <div v-for="(category, key) in categories" :class="currentCategory === key ? 'active' : ''" @click="currentCategory = key">
                        {{ category.title }}
                    </div>
                </div>
                <template v-for="(category, key) in categories" v-if="currentCategory === key">
                    <ul class="list" v-if="category.list.length > 0">
                        <template v-for="item in category.list" v-key="item.dir">
                            <li class="item" :class="item.show ? 'select' : ''" :title="item.info" @click="showPart(item)">
                                <template v-if="item.num !== 0">
                                    <div class="title" :class="'status-'+item.status">
                                        <span class="status">{{ item.statusText }}</span><span class="name">{{ item.title }}</span>
                                        <span class="subs" v-show="item.subs">{{ item.subs }}</span>
                                    </div>
                                    <div class="part-wrapper" v-show="item.show">
                                        <template v-for="part in item.part" v-key="part">
                                            <div
                                                class="part"
                                                :class="current===part?'active':''"
                                                @click="play(key, item, part, $event)"
                                                @dblclick="copyUrl(key, item, part)"
                                            >
                                                {{ part.substring(0,part.lastIndexOf('.')) }}
                                            </div>
                                        </template>
                                    </div>
                                </template>
                                <template v-else>
                                    <div v-if="item.status==='0'" class="title" :class="'status-'+item.status">
                                        <span class="status">{{ item.statusText }}</span><span class="name">{{ item.title }}</span>
                                    </div>
                                    <div
                                        v-else
                                        class="title"
                                        @click="play(key, item, item.nameReg, $event)"
                                        @dblclick="copyUrl(key, item, item.nameReg)"
                                    >
                                        <span class="status">{{ item.statusText }}</span><span class="name">{{ item.title }}</span>
                                    </div>
                                </template>
                            </li>
                        </template>
                    </ul>
                    <div class="no-data" v-else>no data</div>
                </template>
            </aside>
            <div class="video">
                <video v-if="current" id="my-player" class="video-js" :class="theme" controls preload="auto" data-setup="{}"></video>
            </div>
        </div>
    </body>
    <script src="../../common/js/video.min.js"></script>
    <script>
        let isWindows = navigator.appVersion.indexOf('Windows') > 0;
        let domain = 'http://v.noif.fun/videos/';
        let appDom = document.getElementById('app');
        let vm = new Vue({
            el: appDom,
            data() {
                return {
                    theme: 'vjs-theme-sea',
                    current: '',
                    lastUpdate: '',
                    currentCategory: 'Anime',
                    categories: {
                        Anime: {
                            title: 'Anime',
                            show: false,
                            list: []
                        },
                        Film: {
                            title: 'Film',
                            show: false,
                            list: []
                        },
                        Music: {
                            title: 'Music',
                            show: false,
                            list: []
                        }
                    }
                };
            },
            mounted() {
                let href = location.href;
                let index = href.indexOf('#');
                let hash;
                if (index > 0) {
                    hash = href.substr(index + 1);
                    console.log(hash);
                }
                if (hash && this.categories[hash]) {
                    this.currentCategory = hash;
                } else {
                    this.currentCategory = Object.keys(this.categories)[0];
                    window.location.hash = '#' + this.currentCategory;
                }
            },
            watch: {
                currentCategory(current, last) {
                    window.location.hash = '#' + this.currentCategory;
                }
            },
            methods: {
                play(category, item, part, e) {
                    e.stopPropagation();
                    let url = domain + encodeURIComponent(category) + '/' + encodeURIComponent(item.dir) + '/' + encodeURIComponent(part);
                    if (item.dir.indexOf('/') !== -1) {
                        url = url.replace(/%2F/g, '/');
                    }
                    if (this.current === part) {
                        return;
                    }
                    this.current = part;
                    setTimeout(() => {
                        let options = {};
                        if (item.srt) {
                            let suffix = url.substr(url.lastIndexOf('.'));
                            let srtSource = url.replace(new RegExp(suffix, 'g'), '.h5.vtt');
                            console.log(srtSource);
                            options = {
                                tracks: [
                                    {
                                        src: srtSource,
                                        kind: 'captions',
                                        srclang: 'zh',
                                        label: 'Chinese'
                                    }
                                ]
                            };
                        }
                        let isHandled = false;
                        vm.$nextTick(() => {
                            let player = videojs('my-player', options);
                            player.pause();
                            player.src(url);
                            player.load(url);
                            player.ready(() => {
                                let setHeight = setInterval(() => {
                                    let videoJs = document.getElementsByClassName('video-js')[0];
                                    if (videoJs) {
                                        clearInterval(setHeight);
                                        if (isWindows) {
                                            videoJs.style.height = '100%';
                                        } else {
                                            let offsetHeight = document.getElementById('my-player_html5_api').offsetHeight;
                                            videoJs.style.height = offsetHeight + 'px';
                                            document.getElementsByClassName('video')[0].style.height = offsetHeight + 'px';
                                        }
                                    }
                                }, 100);
                            });
                            player.on('error', function (e) {
                                if (!isHandled) {
                                    isHandled = true;
                                    console.log(e);
                                    console.log(player.error().message);
                                    try {
                                        let a = document.createElement('a');
                                        if (isWindows) {
                                            a.href = `vlc:${url}`;
                                        } else {
                                            a.href = `intent:${url}#Intent;package=com.mxtech.videoplayer.pro;S.title=${part};end`;
                                        }
                                        a.click();
                                    } catch (e) {
                                        this.writeClipboard(url);
                                        if (isWindows) {
                                            alert('拉起vlc播放器失败，已复制地址到剪切板');
                                        } else {
                                            alert('拉起mx播放器失败，已复制地址到剪切板');
                                        }
                                    }
                                }
                            });
                        }, 500);
                    });
                },
                copyUrl(category, item, part) {
                    let path = domain + encodeURIComponent(category) + '/' + encodeURIComponent(item.dir) + '/' + encodeURIComponent(part);
                    if (item.dir.indexOf('/') !== -1) {
                        path = path.replace(/%2F/g, '/');
                    }
                    console.log('path', path);
                    this.writeClipboard(path);
                    alert('已复制地址到剪切板');
                },
                showPart(item) {
                    let temp = item.show;
                    for (const key in this.categories) {
                        for (const item of this.categories[key].list) {
                            this.$set(item, 'show', false);
                        }
                    }
                    this.$set(item, 'show', !(temp || false));
                    console.log(item);
                },
                padNumber(num) {
                    let len = num.toString().length;
                    while (len < 2) {
                        num = '0' + num;
                        len++;
                    }
                    return num;
                },
                writeClipboard(text) {
                    let input = document.createElement('input');
                    input.value = text;
                    input.style.display = 'block';
                    input.style.position = 'fixed';
                    input.style.top = '0';
                    input.style.marginTop = '-100px';
                    input.style.zIndex = '-1';
                    document.body.appendChild(input);
                    input.select();
                    input.setSelectionRange(0, input.value.length);
                    document.execCommand('Copy');
                    document.body.removeChild(input);
                }
            }
        });

        fetch(domain + 'list.csv?timestamp=' + new Date().getTime())
            .then((response) => response.text())
            .then((text) => {
                let sp = text.split('\n');
                for (let i = 1; i < sp.length; i++) {
                    if (sp[i].length > 0) {
                        let lineSplit = sp[i].split('|');
                        if (lineSplit.length <= 1) {
                            continue;
                        }
                        let category = lineSplit[0].trim();
                        let dir = lineSplit[1].trim();
                        let nameReg = lineSplit[2].trim();
                        let nums = lineSplit[3].trim();
                        let status = lineSplit[4].trim();
                        let subs = lineSplit[5].trim();
                        let title = lineSplit[6].trim();
                        let info = ''; //lineSplit[6].trim();
                        let part = [];
                        let namesArr = nameReg.split(',');
                        let numsArr = nums.split(',');
                        for (let j = 0; j < namesArr.length; j++) {
                            let name = namesArr[j];
                            if (name.includes('${num}')) {
                                let num = numsArr[j];
                                let startNum = 1;
                                let endNum = num;
                                if (num.includes('-')) {
                                    let numSplit = num.split('-');
                                    startNum = numSplit[0];
                                    endNum = numSplit[1];
                                }
                                for (let p = startNum; p <= endNum; p++) {
                                    part.push(name.replace('${num}', vm.padNumber(p)));
                                }
                            } else {
                                part.push(name);
                            }
                        }
                        let statusText;
                        switch (status) {
                            case '0':
                                statusText = '暂无';
                                nums = '0';
                                break;
                            case '1':
                                statusText = '连载';
                                break;
                            case '2':
                                statusText = '完结';
                                break;
                            default:
                                statusText = '';
                                break;
                        }
                        let list = vm.categories[category].list;
                        list.push({
                            dir: dir,
                            title: title,
                            nameReg: nameReg,
                            srt: false,
                            status: status,
                            statusText: statusText,
                            subs: subs,
                            info: info,
                            part: part
                        });
                    }
                }
            });
        // document.body.addEventListener('touchmove', event => event.preventDefault(), false)
    </script>
</html>
